package models

import (
	"time"

	"github.com/beego/beego/v2/client/orm"
	"weiboxs.com/new_h_glasses/utils"
)

//仓库
type ErpWarehouse struct {
	Id            int64
	DepartmentId  int64
	WarehouseName string
	Pinyin        string
	Status        int
	Summary       string
	CreatedAt     int64
	UpdatedAt     int64
}

//查询
type ErpWarehouseQueryParam struct {
	BaseQueryParam
	Filter string
}

func (a *ErpWarehouse) TableName() string {
	return ErpWarehouseTableName()
}

func ErpWarehouseTableName() string {
	return TableName("erp_warehouse")
}

func GetErpWarehouseById(id int64) (*ErpWarehouse, error) {

	r := new(ErpWarehouse)
	err := orm.NewOrm().QueryTable(ErpWarehouseTableName()).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}

	return r, nil

}

func ErpWarehouseList() []*ErpWarehouse {
	ls := make([]*ErpWarehouse, 0)
	query := orm.NewOrm().QueryTable(ErpWarehouseTableName())
	query = query.Filter("status", 1).Filter("department_id", CurLoginUserInfo.DepartmentId)

	query.OrderBy("-Id").All(&ls)
	return ls
}

func ErpWarehousePageList(params *ErpWarehouseQueryParam) ([]*ErpWarehouse, int64) {

	ls := make([]*ErpWarehouse, 0)

	query := orm.NewOrm().QueryTable(ErpWarehouseTableName())

	if len(params.Filter) > 0 {
		query = query.Filter("warehouse_name__istartswith", params.Filter)
	}

	query = query.Filter("department_id", CurLoginUserInfo.DepartmentId)

	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&ls)

	return ls, total
}

func ErpWarehouseAdd(c *ErpWarehouse) (int64, error) {

	c.Status = 1
	c.Pinyin = utils.ConvertPinyin(c.WarehouseName)
	c.UpdatedAt = time.Now().Unix()
	c.CreatedAt = time.Now().Unix()
	c.DepartmentId = CurLoginUserInfo.DepartmentId

	return orm.NewOrm().Insert(c)
}

func (a *ErpWarehouse) ErpWarehouseEdit(filter ...string) error {

	a.Pinyin = utils.ConvertPinyin(a.WarehouseName)
	a.UpdatedAt = time.Now().Unix()
	a.DepartmentId = CurLoginUserInfo.DepartmentId

	if _, err := orm.NewOrm().Update(a, filter...); err != nil {
		return err
	}
	return nil
}

func ErpWarehouseDel(id int64) error {

	var c ErpWarehouse
	c = ErpWarehouse{Id: id, Status: 2}

	orm.NewOrm().Read(&c)
	if c.Status == 1 {
		c.Status = 2
	} else {
		c.Status = 1
	}

	if _, err := orm.NewOrm().Update(&c, "status"); err != nil {
		return err
	}
	return nil
}
